package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.base.PageView;
import org.gdpu.model.Subject;
import org.gdpu.model.Test;
import org.gdpu.model.TestAnswer;
import org.gdpu.model.TestCategory;
import org.gdpu.service.SubjectService;
import org.gdpu.service.TestAnswerService;
import org.gdpu.service.TestCategoryService;
import org.gdpu.service.TestService;
import org.gdpu.vo.TestVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by HEWI2 on 1/13/14.
 */
@Component("test")
@Scope("prototype")
public class TestAction extends MyActionSupport implements ModelDriven<TestVO> {

    private static final Logger logger = LogManager.getLogger(TestAction.class);

    private final TestVO testVO = new TestVO();
    private Test test = new Test();
    private TestAnswer testAnswer;
    private TestService testService;
    private SubjectService subjectService;
    private TestCategoryService testCategoryService;
    private TestAnswerService testAnswerService;


    public String getList() throws Exception {
        /** 每页显示的结果数 **/
        int maxResult = 10;
        /** 封装的页面数据 **/
        PageView<Test> pageView = new PageView<Test>(maxResult,
                testVO.getPage());
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
                .getMaxResult());// 开始索引

        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        if (testVO.getOrderBy() != null && testVO.getOrderByname() != null&&
                !"".equals(testVO.getOrderBy().trim()) && !"".equals(testVO.getOrderByname().trim())) {
            String orderName = testVO.getOrderByname().trim();
            String orderByname;
            if ("题目编号".equals(orderName)) {
                orderByname = "testId";
            } else if ("题型".equals(orderName)) {
                orderByname = "category.type";
            } else if ("科目".equals(orderName)) {
                orderByname = "subject.subjectName";
            } else {
                orderByname = "id";
            }
            orderBy.put(orderByname, testVO.getOrderBy());
            testVO.setOrderBy(testVO.getOrderBy());
            testVO.setOrderByname(testVO.getOrderByname());
        } else {
            orderBy.put("id", "desc");
        }

        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();
        jpql.append(" and (o.owner = ?1 or o.state = 1)");
        params.add(testVO.getAccount());

        /**标签条件添加**/
        if(testVO.getSearchCategory()!=null && testVO.getSearchSubject()!=null){
            int searchSubject = 0;
            int searchCategory = 0;
            try {
                searchSubject = Integer.valueOf(testVO.getSearchSubject());
                searchCategory = Integer.valueOf(testVO.getSearchCategory());

            } catch (NumberFormatException e) {
                logger.catching(e);
                testVO.setResultMessage("条件选择失败！");
                return ERROR;
            }

            int flag = 2;

            if(!"0".equals(testVO.getSearchSubject().trim())){
                jpql.append(" and o.subject.id = ?").append(flag);
                params.add(searchSubject);
                flag++;
            }

            if(!"0".equals(testVO.getSearchCategory().trim())){
                jpql.append(" and o.category.id = ?").append(flag);
                params.add(searchCategory);
            }

            testVO.setSearchSubject(testVO.getSearchSubject());
            testVO.setSearchCategory(testVO.getSearchCategory());
        }else {
            testVO.setSearchSubject("0");
            testVO.setSearchCategory("0");
        }

        pageView.setQueryResult(testService.getScrollData(Test.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(), orderBy));

        testVO.setPageView(pageView);
        view = "/page/test/testList.jsp";
        return "view";


    }


    @Override
    public String execute() throws Exception {
        Subject subject = subjectService.findSubjectBySubjectName(testVO.getSubject());
        TestCategory testCategory = testCategoryService.findTestCategory(
                testCategoryService.findTestCategoryById(testVO.getCategory()));
        if (subject == null || testCategory == null) {
            testVO.setResultMessage("请选择科目或试题类型！");
            return ERROR;
        }

        if ("单选题".equals(testCategory.getType()) || "多选题".equals(testCategory.getType())
                || "判断题".equals(testCategory.getType())) {
            testAnswer = new TestAnswer(testVO.getAnswerKeys().replaceAll("&nbsp;", " "), testVO.getAnswer().replaceAll("&nbsp;", " "));
        } else if ("填空题".equals(testCategory.getType()) || "问答题".equals(testCategory.getType())) {
            testAnswer = new TestAnswer(testVO.getAnswerKeys().replaceAll("&nbsp;", " "), testVO.getChoices().replaceAll("&nbsp;", " "));
        }
        try {
            testAnswerService.save(testAnswer);
        } catch (Exception e) {
            logger.error(e);
            testVO.setResultMessage("输入答案超长！");
            return ERROR;
        }
        test.setTheme(testVO.getTheme());
        test.setSubject(subject);
        test.setAnswer(testAnswer);
        test.setCategory(testCategory);
        test.setDifficulty(0.0);
        test.setTestId(testService.getMaxTestId());
        test.setOwner(testVO.getOwner());
        test.setState(testVO.getShare());
        try {
            testService.save(test);

        } catch (Exception e) {
            logger.error(e);
            testVO.setResultMessage("输入题目超长！");
            return ERROR;
        }
        testVO.setResultMessage("添加成功！");
        return SUCCESS;
    }


    @Resource(name = "testServiceImpl")
    public void setTestService(TestService testService) {
        this.testService = testService;
    }

    @Resource(name = "subjectServiceImpl")
    public void setSubjectService(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Resource(name = "testCategoryServiceImpl")
    public void setTestCategoryService(TestCategoryService testCategoryService) {
        this.testCategoryService = testCategoryService;
    }

    @Resource(name = "testAnswerServiceImpl")
    public void setTestAnswerService(TestAnswerService testAnswerService) {
        this.testAnswerService = testAnswerService;
    }

    @Override
    public TestVO getModel() {
        return testVO;
    }
}
